require 'rubygems'
require 'sinatra'
require 'haml'
require 'filemagic'
require 'sqlite3'

# 主页
get '/' do
    @projects = Dir.entries('projects').select do |entry|
        not (entry.include? 'svn' or entry =~ /^\.*$/)
    end
    haml :index
end

# project文件浏览
get '/projects/*' do
    path = params[:splat].first
    filePath = 'projects/' + path
    if File.directory? filePath
        @path = path
        haml :listFiles
    else
        @ftype = ftype filePath
        @fformat = fformat filePath
        @file = File.new filePath, 'r'
        begin
            db = SQLite3::Database.new('data/tsukkomi.db')
            result = db.execute('select id, x, y, tsukkomi from tsukkomi where file_path = ? order by id asc', '/' + path)
            if result == nil || result.empty?
                @ts = 'var ts = [];'
            else
                @ts = 'var ts = ' + result_to_js_array(result) + ';'
            end
        rescue
            puts $!
        ensure
            db.close
        end
        haml :tsukkomi
    end
end

# projects中的img浏览
get '/proimg/*' do
    path = params[:splat].first
    send_file path
end

#保存到数据库
post '/save' do
    msg = params[:msg]
    x = params[:x]
    y = params[:y]
    path = params[:path]
    begin
        db = SQLite3::Database.new('data/tsukkomi.db')
        db.execute("insert into tsukkomi(tsukkomi, x, y, file_path, gmt_create) values (?, ?, ?, ?, ?)", msg, x, y, path, Time.new.strftime('%Y-%m-%d %H:%M:%S'))
        db.last_insert_row_id().to_s
    rescue
        puts $!
        'Error occurred!Please contact yue.weny@alibaba-inc.com.'
    ensure
        db.close
    end
end

#从数据库删除
post '/del' do
    dbId = params[:dbId]
    begin
        db = SQLite3::Database.new('data/tsukkomi.db')
        db.execute("delete from tsukkomi where id = ?", dbId)
    rescue
        puts $!
        'Error occurred!Please contact yue.weny@alibaba-inc.com.'
    ensure
        db.close
    end
end

helpers do
    # 判断指定文件的格式化类型，用作代码高亮
    def fformat path
        ext = File.extname path
        if ext == '.rb'
            :ruby
        elsif ext == '.css'
            :css
        elsif ext == '.htm' || ext == '.html'
            :html
        elsif ext == '.groovy'
            :groovy
        elsif ext == '.java'
            :java
        elsif ext == '.js'
            :javascript
        elsif ext == '.json'
            :json
        elsif ext == '.php'
            :php
        elsif ext == '.py'
            :python
        elsif ext == '.sql'
            :sql
        elsif ext == '.xml'
            :xml
        elsif ext == '.vm'
            :html
        elsif ext == '.c' || ext == '.cpp'
            :c
        else
            nil 
        end
    end
    # 判断指定文件类型
    def ftype file
        type = FileMagic.new.file file
        if type =~ /text/
            'txt'
        elsif type =~ /image/
            'img'
        else
            'unknown'
        end
    end
    # 将二维数组的数据库查询结果转换为js的二维数组
    def result_to_js_array result
        is = []
        result.each do |row|
            tmp = '[\'' + row.join('\',\'') + '\']'
            is << tmp
        end
        '[' + is.join(',') + ']'
    end
end

# 404跳转到主页
not_found do
    redirect to('/')
end

configure do
    set :environment, 'production'
    set :port, 65533
end
